package com.sm.service;

import com.sm.dao.*;
import com.sm.model.*;
import com.sm.util.DateUtil;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class MyVipService {

    @Autowired
    private MyVipMapper myVipMapper;
    @Autowired
    private UserVipOrderMapper userVipOrderMapper;
    @Autowired
    private VipDictionaryMapper vipDictionaryMapper;

    @Autowired
    private IncomeDetailMapper incomeDetailMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private SystemInformationService systemInformationService;

    @Autowired
    private AllianceMapper allianceMapper;

    @Autowired
    private DealerMapper dealerMapper;

    /**
     * 获取我的vipId列表
     * @param userId
     * @return
     */
    public List<Integer> getMyVipIdList(Integer userId) {
        List<MyVip> myVips = myVipMapper.listByUserId(userId);
        if (myVips == null || myVips.size() == 0) {
            return null;
        }
        return myVips.stream().map(MyVip::getVipId).map(Long::intValue).collect(Collectors.toList());
    }
    /**
     * 获取我的vipId列表
     * @param userId
     * @return
     */
    public List<MyVip> getMyVipList(Integer userId) {
        List<MyVip> myVips = myVipMapper.listByUserId(userId);
        if (myVips == null || myVips.size() == 0) {
            return null;
        }
        return myVips;
    }

    /**
     * 获取我的VIP
     *
     * @param userId
     * @return
     */
    public List<MyVip> getMyVip(Integer userId) {
        List<MyVip> myVips = new ArrayList<>();
        //判断是否是超级VIP以上的
        boolean isSingle = false;
        List<MyVip> myVipList = myVipMapper.listByUserId(userId);
        for (MyVip myVip : myVipList) {
            if (myVip.getVipType() >= 6) {
                isSingle = true;
            }
        }
        //超级vip以上
        if (isSingle) {
            //返回最高的一个VIP
            myVips.add(myVipList.get(0));
            return myVips;
        } else {
            return myVipList;
        }
    }

    /**
     * 购买过vip后支付回调到这里，新增/续费VIP
     *
     * @param orderNum 订单编号
     */
    @Transactional
    public void notifyInsert(String orderNum) {

        UserVipOrder userVipOrder = userVipOrderMapper.selectByOrderNum(orderNum);
        //订单状态改为已支付
        userVipOrder.setIsPay(1);
        userVipOrderMapper.updateByPrimaryKeySelective(userVipOrder);

        Integer userId = userVipOrder.getUserId();
        String vipIds = userVipOrder.getVipId();
        String[] split = vipIds.split(",");
        //给该用户充值vip
        for (String vipId : split) {
            //查询该用户有没有该会员
            MyVip myVip = myVipMapper.selectByUserIdAndVipId(userId, vipId);
            //vip字典
            VipDictionary vipDictionary = vipDictionaryMapper.selectByPrimaryKey(Long.parseLong(vipId));
            //以前没有充值过
            if (myVip == null) {
                int vipIdInt = Integer.parseInt(vipId);
                MyVip newMyVip = new MyVip(null,
                        userId,
                        vipDictionary.getId(),
                        vipDictionary.getName(),
                        vipDictionary.getPrice(),
                        new Date(),
                        DateUtil.getDateAddYear(new Date(), vipDictionary.getUseTime()),
                        null,
                        vipIdInt);
                //充值会员
                myVipMapper.insert(newMyVip);

                String content = "恭喜你，开通了" + vipDictionary.getName() + ",到期时间为" + DateUtil.formatTime(newMyVip.getExpireTime());
                systemInformationService.insertSysInfo(content, vipDictionary.getName() + "开通成功", userVipOrder.getUserId());

                //返利逻辑
                this.rebate(userId, vipIdInt);

            } else {
                //充值过 过期了
                if (myVip.getExpireTime().before(new Date())) {
                    myVip.setExpireTime(DateUtil.getDateAddYear(new Date(), vipDictionary.getUseTime()));
                } else {
                    //没过期
                    myVip.setExpireTime(DateUtil.getDateAddYear(myVip.getExpireTime(), vipDictionary.getUseTime()));
                }
                String content = "恭喜你，充值了" + vipDictionary.getName() + ",到期时间为" + DateUtil.formatTime(myVip.getExpireTime());
                systemInformationService.insertSysInfo(content, vipDictionary.getName() + "充值成功", userVipOrder.getUserId());

                myVipMapper.updateByPrimaryKeySelective(myVip);
            }
        }
    }

    /**
     * 推荐会员返利
     *
     * @param userId 用户ID
     * @param vipId
     */
    private void rebate(Integer userId, int vipId) {
        //给上级反的钱
        double money = 0;
        //给上上级反的钱
        double ppmoney = 0;
        //上级水内容
        StringBuilder pFlow = new StringBuilder();
        //上上级加流水
        StringBuilder ppFlow = new StringBuilder();
        //我开通的VIP类型 1，VIP  2，超级VIP
        int sourceIncome;
        //我开通的VIP
        if (vipId <= 5) {
            sourceIncome = 1;
        } else {
            //我开通的超级VIP
            sourceIncome = 2;
        }
        //VIP字典
        VipDictionary vipDictionary = vipDictionaryMapper.selectByPrimaryKey(Long.parseLong(String.valueOf(vipId)));
        //我
        User user = userService.selectByPrimaryKey(userId);
        //我的上级
        User parentUser = userService.selectByPrimaryKey(user.getRefereesUserId());

        User parentParentUser = null;
        if (parentUser != null) {
            //我的上上级
            parentParentUser = userService.selectByPrimaryKey(parentUser.getRefereesUserId());
        }
        if (parentUser != null) {
            //上级的等级
            Integer topType = myVipMapper.getTopType(user.getRefereesUserId());

            //如果我开通了超级VIP，并且我的上级是普通会员或者VIP或者超级VIP那么我要自动绑定到131419下面
            //并且给131419 2000佣金
            if (vipId == 6&&(topType==null||topType <= 6)) {
                User boss = userService.selectByRecommendCode("131419");
                user.setRefereesUserId(boss.getUserId());
                userService.updateByPrimaryKeySelective(user);
                parentUser = boss;
                money = 2000;
                pFlow.append(user.getNickName())
                        .append("(")
                        .append(user.getPhone())
                        .append(")购买了")
                        .append(vipDictionary.getName())
                        .append("，金额")
                        .append(vipDictionary.getPrice())
                        .append("元,购买时间：")
                        .append(DateUtil.formatTime(new Date(), "yyyy-MM-dd HH:mm:ss"))
                        .append("，你获得推荐收益：")
                        .append(money)
                        .append("元")
                ;
                //添加流水记录
                IncomeDetail incomeDetail = new IncomeDetail(null, user.getRefereesUserId(), sourceIncome, new Date(), money, pFlow.toString(),user.getUserId());
                incomeDetailMapper.insert(incomeDetail);
                //用户钱包加钱
                parentUser.setBalance(parentUser.getBalance() + money);
                parentUser.setAllIncome(parentUser.getAllIncome() + money);
                userService.updateByPrimaryKeySelective(parentUser);
                //给上级发送消息通知
                String content = "你推荐的用户" + user.getNickName() + "购买了" + vipDictionary.getName() + "你将获得收益" + money + "元，请查收";
                systemInformationService.insertSysInfo(content, "你有一笔收益已到账", parentUser.getUserId());
            }

            //上上级的等级
            Integer ppTopType = null;
            //有上上级，获取上上级的VIP等级
            if (parentUser.getRefereesUserId() != null) {
                ppTopType = myVipMapper.getTopType(parentUser.getRefereesUserId());
            }

            //上级是VIP或用户
            if (topType == null || topType <= 5) {
                return;
            } else if (topType == 6) { //超级VIP
                if (sourceIncome == 1) {
                    money = 100;
                    //判断上上级，如果是合作园给上上级反100元，如果是联盟园，区域经理，131419 返200元
                    if (ppTopType != null) {
                        //上上级是合作园
                        if (ppTopType == 7) {
                            ppmoney = 100;
                        } else if (ppTopType > 7 || "131419".equals(parentParentUser.getRecommendCode())) {
                            //上上级是联盟园｜区域经理｜邀请码是131419
                            ppmoney = 200;
                        }
                    }
                } else {
                    return;
                }
            } else if (topType == 7) {//合作园
                if (sourceIncome == 1) {
                    money = 200;
                } else {
                    money = 1000;
                }
            } else if (topType == 8) { // 联盟园
                if (sourceIncome == 1) {
                    money = 300;
                } else {
                    money = 2000;
                }
            } else if (topType == 9) {// 区域经理
                if (sourceIncome == 1) {
                    money = 300;
                } else {
                    money = 2000;
                }
            }

            pFlow.append(user.getNickName())
                    .append("(")
                    .append(user.getPhone())
                    .append(")购买了")
                    .append(vipDictionary.getName())
                    .append("，金额")
                    .append(vipDictionary.getPrice())
                    .append("元,购买时间：")
                    .append(DateUtil.formatTime(new Date(), "yyyy-MM-dd HH:mm:ss"))
                    .append("，你获得推荐收益：")
                    .append(money)
                    .append("元")
            ;
            if (money == 0) {
                return;
            }
            //添加流水记录
            IncomeDetail incomeDetail = new IncomeDetail(null, user.getRefereesUserId(), sourceIncome, new Date(), money, pFlow.toString(),user.getUserId());
            incomeDetailMapper.insert(incomeDetail);
            //用户钱包加钱
            parentUser.setBalance(parentUser.getBalance() + money);
            parentUser.setAllIncome(parentUser.getAllIncome() + money);
            userService.updateByPrimaryKeySelective(parentUser);
            //给上级发送消息通知
            String content = "你推荐的用户" + user.getNickName() + "购买了" + vipDictionary.getName() + "你将获得收益" + money + "元，请查收";
            systemInformationService.insertSysInfo(content, "你有一笔收益已到账", parentUser.getUserId());

            //给上级加钱
            if (ppmoney == 0) {
                return;
            }
            //上上级有收益
            ppFlow.append(user.getNickName())
                    .append("(")
                    .append(user.getPhone())
                    .append(")购买了")
                    .append(vipDictionary.getName())
                    .append("，金额")
                    .append(vipDictionary.getPrice())
                    .append("元,购买时间：")
                    .append(DateUtil.formatTime(new Date(), "yyyy-MM-dd HH:mm:ss"))
                    .append("，你获得推荐收益：")
                    .append(ppmoney)
                    .append("元")
            ;
            //给上上级添加流水记录
            IncomeDetail ppIncomeDetail = new IncomeDetail(null, parentParentUser.getUserId(), sourceIncome, new Date(), ppmoney, ppFlow.toString(),user.getUserId());
            incomeDetailMapper.insert(ppIncomeDetail);
            //给上上级用户钱包加钱
            parentParentUser.setBalance(parentParentUser.getBalance() + ppmoney);
            parentParentUser.setAllIncome(parentParentUser.getAllIncome() + ppmoney);
            userService.updateByPrimaryKeySelective(parentParentUser);
            String pcontent = "你的下级:" + parentUser.getNickName() + "推荐的用户:" + user.getNickName() + "购买了" + vipDictionary.getName() + "你将获得收益" + ppmoney + "元，请查收";
            systemInformationService.insertSysInfo(pcontent, "你有一笔收益已到账", parentParentUser.getUserId());

        }
    }

    public Integer getTopType(Integer userId) {
        return myVipMapper.getTopType(userId);
    }

    /**
     * 获取用户最高身份
     * @param userId 用户ID
     * @return  0代表普通用户 1VIP 2超级VIP 3合作园 4联盟园 5区域经理
     */
    public Integer getMyTopType(Integer userId) {
        int type = 0;
        Integer topType = myVipMapper.getTopType(userId);
        if (topType != null) {
            if (topType < 6) {
                type = 1;
            } else if (topType == 6) {
                type = 2;
            } else if (topType == 7) {
                type = 3;
            } else if (topType == 8) {
                type = 4;
            } else if (topType == 9) {
                type = 5;
            }
        }
        return type;
    }

    /**
     * 获取下级各个会员等级的数量
     *
     * @param userId
     * @return
     */
    public List<Map<String, Object>> getMyLowerLevelNum(Integer userId) {
        List<Map<String, Object>> list = new ArrayList<>();

        //普通会员人数
        int notVipCount = myVipMapper.countNotVipByParentUserId(userId);

        Map<String, Object> map = new HashMap<>(3);
        map.put("type", 1);
        map.put("name", "会员");
        map.put("count", notVipCount);
        list.add(map);
        //用户自己的最高等级
        User user = userService.selectUserById(userId);
        Integer topType = myVipMapper.getTopType(userId);
        if (topType != null) {
            //VIP
            if (topType > -1) {
                int count = myVipMapper.countByParentUserIdAndVipType(userId, 0, 3, 4, 5);
                Map<String, Object> m = new HashMap<>(3);
                m.put("type", 2);
                m.put("name", "我的VIP");
                m.put("count", count);
                list.add(m);
            }
//            //超级VIP
//            if (topType >= 6) {
//                Map<String, Object> m = new HashMap<>(3);
//                m.put("type", 3);
//                m.put("name", "我的VIP");
//                m.put("count", notVipCount);
//                list.add(m);
//            }
            //合作园
            if (topType >= 7) {
                int count = myVipMapper.countByParentUserIdAndVipType(userId, 6);
                Map<String, Object> m = new HashMap<>(3);
                m.put("type", 3);
                m.put("name", "我的超级VIP");
                m.put("count", count);
                list.add(m);
            }
            //区域经理
            if (topType >= 9) {
                //合作园
                int count = myVipMapper.countByParentUserIdAndVipType(userId, 7);
                Map<String, Object> m = new HashMap<>(3);
                m.put("type", 4);
                m.put("name", "我的合作园");
                m.put("count", count);
                list.add(m);
                //联盟园
                int count2 = myVipMapper.countByParentUserIdAndVipType(userId, 8);
                Map<String, Object> n = new HashMap<>(3);
                n.put("type", 5);
                n.put("name", "我的联盟园");
                n.put("count", count2);
                list.add(n);

                if ("131419".equals(user.getRecommendCode())) {
                    int count4 = myVipMapper.countByParentUserIdAndVipType(userId, 9);
                    Map<String, Object> q = new HashMap<>(3);
                    q.put("type", 7);
                    q.put("name", "我的区域经理");
                    q.put("count", count4);
                    list.add(q);
                }


            }
            //申请列表
            //联盟园数量
            int count3 = allianceMapper.countByRefereesUserId(userId);
            //区域经理数量
            if ("131419".equals(user.getRecommendCode())) {
                count3 += dealerMapper.countByRefereesUserId();
            }
            Map<String, Object> q = new HashMap<>(3);
            q.put("type", 6);
            q.put("name", "申请列表");
            q.put("count", count3);
            list.add(q);

        }
        return list;
    }

    public Integer existType(Integer userId, Integer type) {
        return myVipMapper.existType(userId,type);
    }
}
